<template>
	<view class="edit-page">
		<view class="form-card">
			<view class="field">
				<text class="label">收货人</text>
				<input class="input" v-model="form.receiver" placeholder="请输入收货人" />
			</view>
			<view class="field">
				<text class="label">手机号</text>
				<input class="input" type="number" v-model="form.phone" placeholder="请输入手机号" />
			</view>
			<view class="field">
				<text class="label">省份</text>
				<input class="input" v-model="form.province" placeholder="请输入省份" />
			</view>
			<view class="field">
				<text class="label">城市</text>
				<input class="input" v-model="form.city" placeholder="请输入城市" />
			</view>
			<view class="field">
				<text class="label">区县</text>
				<input class="input" v-model="form.district" placeholder="请输入区/县" />
			</view>
			<view class="field">
				<text class="label">详细地址</text>
				<textarea class="textarea" v-model="form.detail" placeholder="街道、门牌号等"></textarea>
			</view>
		</view>

		<button class="save" :disabled="saving" @click="save">{{ saving ? '保存中...' : '保存' }}</button>
	</view>
</template>

<script>
import { api } from '../../utils/request.js'

export default {
	data(){
		return {
			form: { id: null, receiver:'', phone:'', province:'', city:'', district:'', detail:'' },
			saving: false
		}
	},
	onLoad(query){
		if(query && query.data){
			try{
				const parsed = JSON.parse(decodeURIComponent(query.data));
				this.form = { id: parsed.id, receiver: parsed.receiver || '', phone: parsed.phone || '', province: parsed.province || '', city: parsed.city || '', district: parsed.district || '', detail: parsed.detail || '' };
			}catch{}
		}
	},
	methods:{
		async save(){
			if(!this.form.receiver || !this.form.phone || !this.form.detail){
				uni.showToast({ icon:'none', title:'请完善信息' });
				return;
			}
			this.saving = true;
			try{
				let r;
				if(this.form.id){
					r = await api.updateAddress(this.form);
				}else{
					r = await api.createAddress(this.form);
				}
				if(r.code===0){
					uni.showToast({ title:'保存成功' });
					setTimeout(()=>{ uni.navigateBack(); }, 600);
				}else{
					uni.showToast({ icon:'none', title:r.message||'保存失败' });
				}
			}catch{ uni.showToast({ icon:'none', title:'保存失败' }); }
			finally{ this.saving = false; }
		}
	}
}
</script>

<style>
.edit-page{ padding: 24rpx; }
.form-card{ background:#fff; border-radius: 18rpx; padding: 24rpx; box-shadow: 0 8rpx 24rpx rgba(0,0,0,.05); display:flex; flex-direction: column; gap: 20rpx; }
.field{ display:flex; flex-direction: column; gap: 12rpx; }
.label{ font-size: 26rpx; color:#555; }
.input{ background:#f7f7f8; border-radius: 12rpx; padding: 18rpx 20rpx; font-size: 28rpx; }
.textarea{ background:#f7f7f8; border-radius: 12rpx; padding: 18rpx 20rpx; font-size: 28rpx; min-height: 140rpx; }
.save{ margin-top: 40rpx; background: linear-gradient(135deg,#ff7a45,#ff4d4f); color:#fff; border-radius: 999rpx; padding: 18rpx 0; font-size: 30rpx; }
.save:disabled{ opacity:.6; }
</style>

